<template>
  <div>
    <div class="outputField_title">输出字段列表</div>
    <a-table 
      :columns="columns" 
      :data-source="columnsTable" 
      :pagination="false"
      rowKey="index"
      size="middle"
    >
      <span slot="action" slot-scope="row">
        <a @click="onUpdateOutput(row)">编辑</a>
      </span>
    </a-table>

    <a-modal v-model="visible" title="编辑输出字段" @ok="handleOk" okText="确定" cancelText="取消" :maskClosable="false">
      <!-- 表单 -->
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <!-- 字段名 -->
        <a-form-model-item label="字段名">
          <div> {{form.name}} </div>
          <!-- <a-input v-model="form.name" placeholder="请输入字段名" disabled /> -->
        </a-form-model-item>
        <!-- 显示名 -->
        <a-form-model-item label="显示名" prop="displayName">
          <a-input v-model="form.displayName" placeholder="请输入显示名"/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from 'vuex';
import _ from "lodash";
const columns = [
    { 
      title: '字段名', 
      dataIndex: 'name', 
      align: 'center'
    },
    { 
      title: '字段显示名', 
      dataIndex: 'displayName', 
      align: 'center'
    },
    {
      title: '操作',
      align: 'center',
      scopedSlots: { customRender: 'action' },
      width: 100
    }
]
  export default {
    data() {
      return {
        columns,
        columnsTable: [],
        indicators: [],
        visible: false,
        rules: {
          displayName : [ 
            { required :true, message: '请输入显示名', trigger: 'blur' },
            { max: 100, message: '最大长度为100个字符', trigger: 'blur'  }
          ]
        },
        form: {
          name: '',
          displayName: ''
        },
        timeAsX: null
      }
    },
    props: ['outputForm'],
    watch: {
      columnsTable : {
        handler (val) {
          this.outputForm.output = JSON.parse(JSON.stringify(val))
        },
        deep: true
      },
      visible (val) {
        if (!val) {
          this.form = {}
        }
      }
    },
    computed: {
      ...mapState('custom', ['reportForm']),
      ...mapState('analyseType', ['events', 'measures', 'propertiesEvent', 'propertiesUser']),
      properties () {
        return [ ...this.propertiesEvent, ...this.propertiesUser ]
      },
      eventMap: function() {
        let eventMap = {};
        eventMap['Any'] = {
          name: 'Any',
          displayName: '任意事件'
        };
        for(let i = 0; i < this.events.length; i++) {
          eventMap[this.events[i].name] = this.events[i];
        }
        return eventMap;
      },
      measureMap: function() {
        let measureMap = {};
        for(let i = 0; i < this.measures.length; i++) {
            measureMap[this.measures[i].name] = this.measures[i];
        }
        return measureMap;
      },
      propertyMap: function() {
        let propertyMap = {};
        for(let i = 0; i < this.properties.length; i++) {
          propertyMap[this.properties[i].name] = this.properties[i];
        }
        return propertyMap;
      },
    },
    methods: {
      updateIndicators () {
        this.indicators.splice(0, this.indicators.length);
        const config = this.outputForm.config.config
        let obj = {};
        for(let i = 0; i < config.indicators.length; i++) {
          for(let j = 0; j < config.indicators[i].measure.length; j++) {
            let eventName = config.indicators[i].event;
            let measureName = config.indicators[i].measure[j].name;
            if(!obj[eventName + "_" + measureName]) {
              if(eventName in this.eventMap && measureName in this.measureMap) {
                this.indicators.push({
                  label: this.eventMap[eventName].displayName + "的" + this.measureMap[measureName].displayName,
                  value: eventName + "_" + measureName
                });
                obj[eventName + "_" + measureName] = true;
              }
            }
          }
        }
        if(config.display.orderby !== undefined && config.display.orderby !== "") {
          this.indicator = config.display.orderby;
        } else {
          if(this.indicators.length > 0) {
              this.indicator = this.indicators[0].value;
          }
        }
      },
      updateTimeAsX: function() {
        this.timeAsX = (this.outputForm.config.time.unit !== 'none');
      },
      updateTableColumns () {
        this.columnsTable.splice(0, this.columnsTable.length)
        const config = this.outputForm.config.config
        if(this.timeAsX  || config.dimensions.length === 0) {
          this.columnsTable.push({
              displayName: '时间',
              name: 'date'
          });
        }
        for(let i = 0; i < config.dimensions.length; i++) {
          if(config.dimensions[i] in this.propertyMap) {
            this.columnsTable.push({
              displayName: this.propertyMap[config.dimensions[i]].displayName,
              name: config.dimensions[i]
            });
          }
        }
        for(let i = 0; i < this.indicators.length; i++) {
          this.columnsTable.push({
            displayName: this.indicators[i].label,
            name: this.indicators[i].value
          });
        }
        
      },
      onUpdateOutput (row) {
        this.visible = true
        this.form = { ...row }
      },
      handleOk () {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.columnsTable.splice(this.form.index, 1, JSON.parse(JSON.stringify(this.form)))
            this.visible = false
          }
        });
      },
    },
    mounted() {
      this.updateIndicators()
      this.updateTimeAsX()
        let editBefore = _.cloneDeep(this.outputForm.output),
            outputfield = [];
        this.updateTableColumns()
        this.columnsTable.forEach(column => {
          let index = editBefore.findIndex(value => {
            return column.name == value.name;
          })
          if (index > -1) {
            outputfield.push(editBefore[index])
          } else if (index == -1) {
            outputfield.push(column)
          }
        })
        outputfield.forEach((columns,index) => {
          outputfield[index].index = index
        })
        this.columnsTable = outputfield;
    },
  }
</script>

<style scoped>
.outputField_title{
  font-size: 16px;
  font-weight: 500;
  color: rgba(0,0,0,.85);
  margin-bottom: 24px;
  margin-top: 12px;
}
</style>